<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		phpinfo();
	}
	
	//QQ回调地址
	public function qq()
	{
		if(!isset($_SESSION)){
			session_start();
		}
		require_once("../web/Connect2.1/API/qqConnectAPI.php");
		$qc = new QC();
		$access_token = $qc->qq_callback();
		$openid = $qc->get_openid();
		if ($access_token && $openid)
		{
			$qc = new QC($access_token,$openid);
			$user_message = $qc->get_user_info();
			
			if ($user_message)
			{
				$this->load->model('User_model');
				$user = $this->User_model->get_user_by_qqopenid($openid);
				if (!$user)
				{
					//第一次QQ授权登录
					//录入用户信息
					$data = array(
						'addtime'=>time(),
						'status'=>1,
						'validmobile'=>1,
						'lastip'=>_ip_long(),
						'user_source'=>2, //QQ登录
						'usertype'=>1,
						'userlevel'=>0,
						'qq_openid'=>$openid
					);
					$data['sex'] = 0;
					if ($user_message['gender'] == '男')
					{
						$data['sex'] = 1;
					}
					else if ($user_message['gender'] == '女')
					{
						$data['sex'] = 2;
					}
					
					$data['nickname'] = $user_message['nickname'];
					$data['realname'] = $user_message['nickname'];
					$data['city'] = $user_message['city']&&strstr($user_message['city'], '市')?$user_message['city']:$user_message['city'].'市';
					$data['userlogo'] = $user_message["figureurl_qq_2"]?$user_message["figureurl_qq_2"]:'';
					$userid = $this->User_model->insert_string($data);
					$data_detail = array('userid'=>$userid,'safety'=>2);
					$this->User_model->set_table('user_detail');
					$this->User_model->insert($data_detail);
					$data_memo = array('userid'=>$userid,);
					$this->User_model->set_table('user_memo');
					$this->User_model->insert($data_memo);
					//begin-初始化相册
					$this->load->model('Album_model');
					$data_album = array('userid'=>$userid,
						'title'=>'精选作品',
						'memo'=>'系统默认',
						'kind'=>1,
						'status'=>1,
						'addtime'=>time(),
					);
					$this->Album_model->insert($data_album);
					//end-初始化相册
					
					$res['code'] = 200;
					
					// 设置session
					$user_info = $this->User_model->get_user_by_ids($userid);
					$this->security_code = md5(session_id().$userid);
					
					$this->load->library('encrypt');
					$str = $this->encrypt->encode($userid);
					$str = md5($this->config->item('encryption_key').$str).$str;
					$this->input->set_cookie('loginUser', $str, 0, XT_DOMAIN);
					$this->input->set_cookie('loginCode', $this->security_code, 0, XT_DOMAIN);
					$this->User_model->set_table('user');
					$this->User_model->login_update($userid, time(), _ip_long());
					$this->loginUser = $user_info;
					
					redirect('/home/qqback/1');
				}
				else
				{
					$this->security_code = md5(session_id().$user['id']);
					$expire = 0;
					$this->load->library('encrypt');
					$str = $this->encrypt->encode($user['id']);
					$str = md5($this->config->item('encryption_key').$str).$str;
					$this->input->set_cookie('loginUser', $str, $expire, XT_DOMAIN);
					$this->input->set_cookie('loginCode', $this->security_code, $expire, XT_DOMAIN);
					$this->User_model->login_update($user['id'], time(), _ip_long());
					$this->loginUser = $user;
					$param = array('ver'=>'v3');
					$this->res['data']['login_userid'] = _get_key_val($user['id']);
					$this->res['data']['usertype'] = $user['usertype'];
					
					redirect('/home/qqback');
				}
			}
		}
		
		//第三方登录失败
		redirect('/user/login');
	}

	//微博回调地址
	public function weibo()
	{
		if(!isset($_SESSION)){
	    	session_start();
		}
		include_once( '../web/libweibo/config.php' );
		include_once( '../web/libweibo/saetv2.ex.class.php' );
		$weibo = array();
		$weibo = _get_config("weibo_app");
		$o = new SaeTOAuthV2( $weibo["app_key"] , $weibo["app_sercet"] );
		$token = "";
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = "http://www.mobooker.com/manager/weibologin";
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}
		$this->log($token);
		if ($token) {
			//第三方登录成功
			$_SESSION['token'] = $token;
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
			
			//获取用户信息
			$c = new SaeTClientV2( $weibo["app_key"] , $weibo["app_sercet"] , $token['access_token'] );
// 			$ms  = $c->home_timeline(); // done
// 			$uid_get = $c->get_uid();
// 			$uid = $uid_get['uid'];
// 			echo $uid;die;
			$user_message = $c->show_user_by_id( $token["uid"]);//根据ID获取用户等基本信息
			
			$this->load->model('User_model');
			$user = $this->User_model->get_user_by_weibouid($token["uid"]);
			if (!$user && $user_message)
			{
				//录入用户信息
				$data = array(
					'addtime'=>time(),
					'status'=>1,
					'validmobile'=>1,
					'lastip'=>_ip_long(),
					'user_source'=>1, //微博登录
					'usertype'=>1,
					'userlevel'=>0,
					'weibo_uid'=>$token["uid"]
				);
				$data['sex'] = 0;
				if ($user_message['gender'] == 'm')
				{
					$data['sex'] = 1;
				}
				else if ($user_message['gender'] == 'f')
				{
					$data['sex'] = 2;
				}
				
				$data['nickname'] = $user_message['screen_name'];
				$data['realname'] = $user_message['name'];
				$data['city'] = '';
				if ($user_message['location'])
				{
					$location_arr = explode(" ", $user_message['location']);
					if (count($location_arr) > 1)
					{
						$data['city'] = $location_arr[1]&&strstr($location_arr[1], '市')?$location_arr[1]:$location_arr[1].'市';
					}
				}
				$data['userlogo'] = $user_message["avatar_large"]?$user_message["avatar_large"]:'';
				$userid = $this->User_model->insert_string($data);
				$data_detail = array('userid'=>$userid,'safety'=>2);
				$this->User_model->set_table('user_detail');
				$this->User_model->insert($data_detail);
				$data_memo = array('userid'=>$userid,);
				$this->User_model->set_table('user_memo');
				$this->User_model->insert($data_memo);
				//begin-初始化相册
				$this->load->model('Album_model');
				$data_album = array('userid'=>$userid,
					'title'=>'精选作品',
					'memo'=>'系统默认',
					'kind'=>1,
					'status'=>1,
					'addtime'=>time(),
				);
				$this->Album_model->insert($data_album);
				//end-初始化相册
				
				$res['code'] = 200;
				
				// 设置session
				$user_info = $this->User_model->get_user_by_ids($userid);
				$this->security_code = md5(session_id().$userid);
				
				$this->load->library('encrypt');
				$str = $this->encrypt->encode($userid);
				$str = md5($this->config->item('encryption_key').$str).$str;
				$this->input->set_cookie('loginUser', $str, 0, XT_DOMAIN);
				$this->input->set_cookie('loginCode', $this->security_code, 0, XT_DOMAIN);
				$this->User_model->set_table('user');
				$this->User_model->login_update($userid, time(), _ip_long());
				$this->loginUser = $user_info;
				
				redirect('/home/index/1');
			}
			else
			{
				$this->security_code = md5(session_id().$user['id']);
				$expire = 0;
				$this->load->library('encrypt');
				$str = $this->encrypt->encode($user['id']);
				$str = md5($this->config->item('encryption_key').$str).$str;
				$this->input->set_cookie('loginUser', $str, $expire, XT_DOMAIN);
				$this->input->set_cookie('loginCode', $this->security_code, $expire, XT_DOMAIN);
				$this->User_model->login_update($user['id'], time(), _ip_long());
				$this->loginUser = $user;
				$param = array('ver'=>'v3');
				$this->res['data']['login_userid'] = _get_key_val($user['id']);
				$this->res['data']['usertype'] = $user['usertype'];
				
				redirect('/home');
			}
			
		}
		//第三方登录失败
		redirect('/user/login');
	}
	
	//用户选择分类
	public function type($type="webo")
	{
		if ($this->input->is_post())
		{
			$uid = $this->loginID;
			$usertype = $this->input->post('usertype');
			$data['usertype'] = $usertype;
            //记录用户已选择用户类型，2016-04-11 edit by lvwei
			$data['usertype_seled'] = '1';
			$this->load->model('User_model');
			$this->User_model->update_by_id($uid,$data);
			if ($type == "qq")
			{
				redirect("/home/qqback");
			}
			redirect("/home");
		}
	}
	
	//记录日志
	private function log($content)
	{
		$this->load->model('Debug_model');
		$data['url'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$data['content'] = is_array($content)?serialize($content):$content;
		$data['create_time'] = date("Y-m-d H:i:s");
		$this->Debug_model->insert($data);
	}
	
	//跳转
	private function redirect_home()
	{
		$this->load->model('Ad_model');
		$adlist = $this->Ad_model->get_ads_by_code('home_top_banner');
		
		$underBanAdList = $this->Ad_model->get_ads_by_code('home_under_banner');
		
		$btModelAdList = $this->Ad_model->get_ads_by_code('home_between_model');
		
		$this->load->model('Recommend_model');
		$this->load->model('Userdetail_model');
		$this->load->model('Usernum_model');
		
		$arrWhere = array('usertype'=>1,'status<>'=>-1,'userlevel'=>1,'sex'=>2);
		$feild = 'user.id,nickname,userlogo,company,showimg,showimg2,city';
		$rmdlist1 = $this->Recommend_model->get_user_list($arrWhere, $feild, 10);
		if(!empty($rmdlist1)) {
			foreach ($rmdlist1 as  $key =>$rmd_info) {
				$info =  $this->Userdetail_model->get_info_by_id($rmd_info['id']);
				$rmdlist1[$key]['detail_info'] = $info;
			}
		}
		
		// 女模
		$arrWhere = array('usertype'=>1,'status<>'=>-1, 'sex'=>2, 'nickname<>'=>'');
		$rmdlist2 = $this->Recommend_model->get_user_list($arrWhere, $feild, 12);
		//         echo $this->Recommend_model->db->last_query();die;
		//获取推荐人的详细信息
		if(!empty($rmdlist2)) {
			foreach ($rmdlist2 as  $key =>$rmd_info) {
				$info =  $this->Userdetail_model->get_info_by_userid($rmd_info['id']);
				$numInfo = $this->Usernum_model->get_info_by_userid($rmd_info['id']);
				$rmdlist2[$key]['detail_info'] = $info;
				$rmdlist2[$key]['num_info'] = $numInfo;
			}
		}
		
		$arrWhere = array('usertype'=>1,'status<>'=>-1,'userlevel'=>1,'sex'=>1);
		$rmdlist3 = $this->Recommend_model->get_user_list($arrWhere, $feild, 10);
		//获取推荐人的详细信息
		if(!empty($rmdlist3)) {
			foreach ($rmdlist3 as  $key =>$rmd_info) {
				$info =  $this->Userdetail_model->get_info_by_id($rmd_info['id']);
				$rmdlist3[$key]['detail_info'] = $info;
			}
		}
		
		// 男模
		$arrWhere = array('usertype'=>1,'status<>'=>-1,'sex'=>1,'nickname<>'=>'');
		$rmdlist4 = $this->Recommend_model->get_user_list($arrWhere, $feild, 12);
		//获取推荐人的详细信息
		if(!empty($rmdlist4)) {
			foreach ($rmdlist4 as  $key =>$rmd_info) {
				$info =  $this->Userdetail_model->get_info_by_userid($rmd_info['id']);
				//                 echo $this->Userdetail_model->db->last_query()."<br/>";
				$numInfo = $this->Usernum_model->get_info_by_userid($rmd_info['id']);
				$rmdlist4[$key]['num_info'] = $numInfo;
				$rmdlist4[$key]['detail_info'] = $info;
			}
			//             die;
		}
		
		// 机构
		$arrWhere = array('usertype'=>2,'status<>'=>-1,'nickname<>'=>'');
		$rmdlist5 = $this->Recommend_model->get_user_list($arrWhere, $feild, 10);
		$typeArr = _get_config('type');
		$insTypeArr = $typeArr[2];
		if (!empty($rmdlist5)) {
			foreach($rmdlist5 as $key=>$rmd_info) {
				$typeStr = '';
				$info =  $this->Userdetail_model->get_info_by_userid($rmd_info['id']);
				if (!empty($info['type'])) {
					if (strstr($info['type'], ',')) {
						$infoArr= explode(',', $info['type']);
					} else {
						$typeStr = $insTypeArr[$info['type']];
					}
				}
		
				if (!empty($infoArr)) {
					foreach($infoArr as $it) {
						$typeStr .= ','.$insTypeArr[$it];
					}
				}
		
				$info['type_str'] = ltrim($typeStr, ',');
		
				$rmdlist5[$key]['detail_info'] = $info;
			}
		}
		
		
		// 通告
		$this->load->model('Recommend_model');
		$fields = 'activity.id,title,img,summary,workfee,activity.addtime,begtime,inendtime,place,category,type,innum,innumfake';
		$arrWhere = array('display'=>1, 'status'=>1);
		$actlist1 = $this->Recommend_model->get_act_list($arrWhere, $fields, 6);
		if (!empty($actlist1)) {
			foreach ($actlist1 as $k=>$n) {
				$actlist1[$k]['w_time'] = $n['begtime']&&is_numeric($n['begtime']) ? (date('Y-m-d', (int)$n['begtime'])) : '';
				$actlist1[$k]['endtime'] = date('Y-m-d', $n['inendtime']);
			}
		}
		
		$result = array(
			'adlist' => $adlist,
			'rmdlist1' => $underBanAdList,
			'rmdlist2' => $rmdlist2,
			'rmdlist3' => $btModelAdList,
			'rmdlist4' => $rmdlist4,
			'rmdlist5' => $rmdlist5,
			'actlist1' => $actlist1,
		);
		return $result;
	}
}
?>